﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Company.Utility.BaseEnums;
using Company.Utility.Encrypt;
using Company.Utility.Extensions;
using Newtonsoft.Json;

namespace Company.Utility
{
    public class UmengHelper
    {
        protected static readonly string SendUrl = "http://msg.umeng.com/api/send";

        /// <summary>
        /// 使用友盟API发送通知（IOS）
        /// </summary>

        private static UpushMessageData IOSSendNotificationByDevToken(string message, string userId, UmengParm umengParm)
        {
            try
            {
                string url = SendUrl;
                string app_master_secret = ReadConfig.ReadAppSetting("IOS_App_Master_Secret");
                var sendData = new
                {
                    appkey = ReadConfig.ReadAppSetting("IOS_Appkey"),
                    timestamp = "" + DateTime.Now.ConvertDateTimeInt() + "",
                    device_tokens = userId,
                    type = "listcast",
                    payload = new
                    {
                        aps = new
                        {
                            alert = message,
                            sound = "default",
                            type = umengParm.Type,
                            id = umengParm.Id,

                        }
                    },
                    production_mode = "false",//true/false
                    description = "app消息推送"
                };
                string mysign =MD5Helper.GetMd5Hash("POST" + url + JsonConvert.SerializeObject(sendData) + app_master_secret);
                url = url + "?sign=" + mysign;
                var result = JsonConvert.DeserializeObject<UpushMessageData>(HttpClientHelper.GetHtml(url, JsonConvert.SerializeObject(sendData)));
                result.IsSuccess = result.ret == "SUCCESS";
                return result;
            }
            catch
            {
                return new UpushMessageData() { IsSuccess = false };
            }
        }
        /// <summary>
        /// 使用友盟API发送通知（Android）
        /// </summary>
        private static UpushMessageData AndroidSendNotificationByDevToken(string tokens, string title, string message, string userId, UmengParm umengParm)
        {
            try
            {
                string url = SendUrl;
                string app_master_secret = ReadConfig.ReadAppSetting("Android_App_Master_Secret");
                var sendData = new
                {
                    appkey = ReadConfig.ReadAppSetting("Android_Appkey"),
                    timestamp = "" + DateTime.Now.ConvertDateTimeInt() + "",
                    device_tokens = userId,
                    type = "listcast",
                    payload = new
                    {
                        display_type = "notification",// 通知，notification
                        body = new
                        {
                            ticker = tokens,
                            title = title,
                            sound = "",
                            text = message,
                            after_open = "go_app",
                            activity = "com.zmd.ywm",
                            type = umengParm.Type,
                            id = umengParm.Id,
                        }
                    },
                    production_mode = "true",//true/false
                    description = "app消息推送"
                };
                string mysign = MD5Helper.GetMd5Hash("POST" + url + JsonConvert.SerializeObject(sendData) + app_master_secret);
                url = url + "?sign=" + mysign;
                var result = JsonConvert.DeserializeObject<UpushMessageData>(HttpClientHelper.GetHtml(url, JsonConvert.SerializeObject(sendData)));
                result.IsSuccess = result.ret == "SUCCESS";
                return result;
            }
            catch
            {
                return new UpushMessageData() { IsSuccess = false };
            }
        }


        public static List<UpushUserData> UpushByTokens(string title, string contents, List<UpushUserData> dtUser,
            UmengParm upParm)
        {
            var tokenbyios = dtUser.Where(x => !string.IsNullOrEmpty(x.UpushDevToken) && x.UpushDevType == Enum_DeviceType.IOS).ToList();
            var tokenbyandroid = dtUser.Where(x => !string.IsNullOrEmpty(x.UpushDevToken) && x.UpushDevType == Enum_DeviceType.Android)
                .ToList();
            if (tokenbyandroid.Any())
            {
                tokenbyandroid.FetchNext(500, x =>
                {
                    var users = string.Join(",", x.Select(y => y.UpushDevToken));
                    var State = 0;
                    if (AndroidSendNotificationByDevToken(title, title, contents, users, upParm).IsSuccess)
                    {
                        State = 1;
                    }
                    else
                    {
                        State = 2;
                    }
                    x.ToList().ForEach(y => y.ResiveState = State);
                });
            }
            if (tokenbyios.Any())
            {
                tokenbyios.FetchNext(500, x =>
                {
                    var users = string.Join(",", x.Select(y => y.UpushDevToken));
                    var State = 0;
                    if (IOSSendNotificationByDevToken(contents, users, upParm).IsSuccess)
                    {
                        State = 1;
                    }
                    else
                    {
                        State = 2;
                    }
                    x.ToList().ForEach(y => y.ResiveState = State);
                });
            }
            return tokenbyandroid.Concat(tokenbyios).ToList();
        }
    }
    public class UpushUserData
    {
        /// <summary>
        /// 消息接收编号，用于接收记录状态变更后进行持久化
        /// </summary>
        public Guid ResiveId { get; set; }
        /// <summary>
        /// 回调接收记录的状态
        /// </summary>
        public int ResiveState { get; set; }
        /// <summary>
        /// 友盟设备号
        /// </summary>
        public string UpushDevToken { get; set; }
        /// <summary>
        /// 循环推送周期
        /// </summary>
        public Enum_MessageCycle PushCycle { get; set; }
        /// <summary>
        /// 友盟设备类型
        /// </summary>
        public Enum_DeviceType? UpushDevType { get; set; }
    }
    public class UpushMessageData
    {
        public string ret { get; set; }
        public UpushMessageChildData data { get; set; }

        public bool IsSuccess { get; set; }
    }

    public class UpushMessageChildData
    {
        public string error_code { get; set; }
        public string appkey { get; set; }
        public string ip { get; set; }
    }

    /// <summary>
    /// 友盟自定义参数
    /// </summary>
    public class UmengParm
    {
        /// <summary>
        /// 跳转类型
        /// </summary>
        public int Type { get; set; }
        /// <summary>
        /// ID
        /// </summary>
        public string Id { get; set; }
    }
}
